package com.eleadin.ruleengine.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author jiangchen
 * @Description 获取IP、Port、应用名，写入系统环境变量给log4j2读取
 * @date 2022/04/22 11:28
 */
@Configuration
public class WebLogConfig implements WebMvcConfigurer {
    @Value("${spring.application.name}")
    private String appName;
    @Value("${server.port}")
    private int port;

    /**
     * 获得本机的内网地址（String）
     */
    private String getLocalIp(){
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            return "unknown-ip";
        }
    }
    /**
     * 设置 "local-ip" system 变量，给log4j2 配置使用：
     */
    @PostConstruct
    public void postConstruct(){
        String localIp = getLocalIp();
        System.setProperty("current-app-name", appName);
        System.setProperty("local-port", Integer.toString(port));
        System.setProperty("local-ip", localIp );
    }
}
